<!--<template>-->
<!--  <div class="app-container">-->
<!--    &lt;!&ndash; 顶部返回文字链接 &ndash;&gt;-->
<!--    <a href="javascript:void(0)" class="back-link" @click="handleBack">-->
<!--      <span>< 返回</span>-->
<!--    </a>-->

<!--    <h2 class="form-title">文章发布</h2>-->

<!--    <el-form label-width="120px" class="article-form" :model="articleInfo">-->
<!--      &lt;!&ndash; 标题输入框 &ndash;&gt;-->
<!--      <el-form-item>-->
<!--        <el-input-->
<!--          v-model="articleInfo.title"-->
<!--          placeholder="请输入文章标题（最多50个字）"-->
<!--          class="article-title-input"-->
<!--          maxlength="100"-->
<!--          @input="checkTitleLength"-->
<!--        />-->
<!--        <div class="title-error" v-if="titleError">{{ titleError }}</div>-->
<!--      </el-form-item>-->

<!--      &lt;!&ndash; 正文编辑器 &ndash;&gt;-->
<!--      <el-form-item>-->
<!--        <div class="editor-container">-->
<!--          <Toolbar class="editor-toolbar" :editor="editor" :defaultConfig="toolbarConfig"/>-->
<!--          <Editor-->
<!--            class="editor-content"-->
<!--            v-model="articleInfo.content"-->
<!--            :defaultConfig="editorConfig"-->
<!--            @onCreated="onEditorCreated"-->
<!--          />-->
<!--        </div>-->
<!--      </el-form-item>-->

<!--      &lt;!&ndash; 封面上传 &ndash;&gt;-->
<!--      &lt;!&ndash; 封面上传 &ndash;&gt;-->
<!--      <el-form-item label="文章封面" class="cover-align">-->
<!--        <el-upload-->
<!--          class="cover-uploader"-->
<!--          action="http://localhost:8000/api/oss/upload"-->
<!--          :show-file-list="false"-->
<!--          :on-success="handleCoverSuccess"-->
<!--          :before-upload="beforeCoverUpload"-->
<!--        >-->
<!--          <img v-if="articleInfo.cover" :src="articleInfo.cover" class="cover-image"/>-->
<!--          <div v-else class="upload-placeholder">-->
<!--            <i class="el-icon-plus cover-uploader-icon"></i>-->
<!--            <div class="upload-text">点击上传封面图</div>-->
<!--            <div class="upload-hint">建议尺寸 800×450，JPG/PNG 格式，大小 ≤ 2MB</div>-->
<!--          </div>-->
<!--        </el-upload>-->
<!--      </el-form-item>-->


<!--      &lt;!&ndash; 按钮组 &ndash;&gt;-->
<!--      <el-form-item>-->
<!--        <div class="btn-group">-->
<!--          <el-button :disabled="saveBtnDisabled" @click="saveAsDraft" class="btn-save-draft">-->
<!--            保存草稿-->
<!--          </el-button>-->
<!--          <el-button type="primary" :disabled="saveBtnDisabled" @click="publishArticle" class="btn-publish">-->
<!--            发布文章-->
<!--          </el-button>-->
<!--        </div>-->
<!--      </el-form-item>-->
<!--    </el-form>-->
<!--  </div>-->
<!--</template>-->

<!--<script>-->
<!--import {Editor, Toolbar} from '@wangeditor/editor-for-vue'-->
<!--import '@wangeditor/editor/dist/css/style.css'-->
<!--import articleApi from '@/api/article'-->

<!--const defaultForm = {-->
<!--  title: '',-->
<!--  content: '',-->
<!--  cover: '',-->
<!--}-->

<!--export default {-->
<!--  layout: 'blank',-->
<!--  components: {Editor, Toolbar},-->
<!--  data() {-->
<!--    return {-->
<!--      articleInfo: {...defaultForm},-->
<!--      saveBtnDisabled: false,-->
<!--      editor: null,-->
<!--      articleId: '',-->
<!--      titleLength: 0,-->
<!--      titleError: '',-->
<!--      toolbarConfig: {-->
<!--        excludeKeys: ['uploadVideo', 'group-video'],-->
<!--      },-->
<!--      editorConfig: {-->
<!--        placeholder: '请在此输入文章正文内容...',-->
<!--        MENU_CONF: {-->
<!--          uploadImage: {-->
<!--            server: 'http://localhost:8000/api/oss/upload',-->
<!--            fieldName: 'file',-->
<!--            maxFileSize: 2 * 1024 * 1024,-->
<!--            allowedFileTypes: ['image/jpeg', 'image/png'],-->
<!--            customInsert: (res, insertImgFn) => {-->
<!--              // res 就是服务器返回的整个对象-->
<!--              if (res.success && res.data) {-->
<!--                insertImgFn(res.data)  // 直接传字符串地址-->
<!--              } else {-->
<!--                // 你可以用编辑器内部的消息提示或者自己写-->
<!--                alert('图片上传失败，请重试')-->
<!--              }-->
<!--            },-->
<!--            onSuccess(file, res) {-->
<!--              console.log('上传成功', res)-->
<!--            },-->
<!--            onFailed(file, res) {-->
<!--              console.error('上传失败', res)-->
<!--            },-->
<!--          }-->
<!--        },-->
<!--      },-->
<!--    }-->
<!--  },-->
<!--  methods: {-->
<!--    checkTitleLength() {-->
<!--      this.titleLength = this.articleInfo.title.length-->
<!--      if (this.titleLength < 5) {-->
<!--        this.titleError = '标题长度不能少于5个字符'-->
<!--        this.saveBtnDisabled = true-->
<!--      } else if (this.titleLength > 50) {-->
<!--        this.titleError = '标题长度不能超过50个字符'-->
<!--        this.saveBtnDisabled = true-->
<!--      } else {-->
<!--        this.titleError = ''-->
<!--        this.saveBtnDisabled = false-->
<!--      }-->
<!--    },-->
<!--    onEditorCreated(editor) {-->
<!--      this.editor = editor-->
<!--    },-->
<!--    beforeDestroy() {-->
<!--      if (this.editor) {-->
<!--        this.editor.destroy()-->
<!--        this.editor = null-->
<!--      }-->
<!--    },-->
<!--    beforeCoverUpload(file) {-->
<!--      const isValid = ['image/jpeg', 'image/png'].includes(file.type)-->
<!--      const isLt2M = file.size / 1024 / 1024 < 2-->
<!--      if (!isValid) this.$message.error('仅支持 JPG/PNG 格式图片！')-->
<!--      if (!isLt2M) this.$message.error('图片大小不能超过 2MB！')-->
<!--      return isValid && isLt2M-->
<!--    },-->
<!--    handleCoverSuccess(response) {-->
<!--      if (response.code === 20000) {-->
<!--        this.articleInfo.cover = response.data-->
<!--        this.$message.success('封面上传成功')-->
<!--      } else {-->
<!--        this.$message.error('封面上传失败：' + response.message)-->
<!--      }-->
<!--    },-->
<!--    handleBack() {-->
<!--      this.$confirm('是否将当前内容保存为草稿？', '提示', {-->
<!--        confirmButtonText: '保存',-->
<!--        cancelButtonText: '不保存',-->
<!--        distinguishCancelAndClose: true,-->
<!--        type: 'warning',-->
<!--      })-->
<!--        .then(() => {-->
<!--          this.saveAsDraft()-->
<!--          this.$router.go(-1)-->
<!--        })-->
<!--        .catch((action) => {-->
<!--          if (action === 'cancel') {-->
<!--            this.$router.go(-1)-->
<!--          }-->
<!--        })-->
<!--    },-->
<!--    publishArticle() {-->
<!--      this.saveOrUpdate('publish')-->
<!--    },-->
<!--    saveAsDraft() {-->
<!--      this.saveOrUpdate('draft')-->
<!--    },-->
<!--    saveOrUpdate(type) {-->
<!--      if (!this.articleInfo.title) {-->
<!--        this.$message.error('请输入文章标题')-->
<!--        return-->
<!--      }-->
<!--      if (!this.articleInfo.content) {-->
<!--        this.$message.error('请输入文章正文')-->
<!--        return-->
<!--      }-->

<!--      const saveType = {-->
<!--        publish: '发布',-->
<!--        draft: '保存为草稿',-->
<!--      }-->

<!--      console.log(`文章已${saveType[type]}:`, this.articleInfo)-->
<!--      this.$message.success(`文章${saveType[type]}成功`)-->
<!--    },-->
<!--  },-->
<!--}-->
<!--</script>-->
<template>
  <div class="app-container">
    <!-- 顶部返回文字链接 -->
    <a href="javascript:void(0)" class="back-link" @click="handleBack">
      <span>< 返回</span>
    </a>

    <h2 class="form-title">文章发布</h2>

    <el-form label-width="120px" class="article-form" :model="articleInfo">
      <!-- 标题输入框 -->
      <el-form-item>
        <el-input
          v-model="articleInfo.title"
          placeholder="请输入文章标题（最多50个字）"
          class="article-title-input"
          maxlength="100"
          @input="checkTitleLength"
        />
        <div class="title-error" v-if="titleError">{{ titleError }}</div>
      </el-form-item>

      <!-- 正文编辑器 -->
      <el-form-item>
        <div class="editor-container">
          <Toolbar class="editor-toolbar" :editor="editor" :defaultConfig="toolbarConfig"/>
          <Editor
            class="editor-content"
            v-model="articleInfo.content"
            :defaultConfig="editorConfig"
            @onCreated="onEditorCreated"
          />
        </div>
      </el-form-item>

      <!-- 封面上传 -->
      <el-form-item label="文章封面" class="cover-align">
        <el-upload
          class="cover-uploader"
          action="http://localhost:8000/api/oss/upload"
          :show-file-list="false"
          :on-success="handleCoverSuccess"
          :before-upload="beforeCoverUpload"
        >
          <img v-if="articleInfo.cover" :src="articleInfo.cover" class="cover-image"/>
          <div v-else class="upload-placeholder">
            <i class="el-icon-plus cover-uploader-icon"></i>
            <div class="upload-text">点击上传封面图</div>
            <div class="upload-hint">建议尺寸 800×450，JPG/PNG 格式，大小 ≤ 2MB</div>
          </div>
        </el-upload>
      </el-form-item>

      <!-- 按钮组 -->
      <el-form-item>
        <div class="btn-group">
          <el-button :disabled="saveBtnDisabled" @click="saveAsDraft" class="btn-save-draft">
            保存草稿
          </el-button>
          <el-button type="primary" :disabled="saveBtnDisabled" @click="publishArticle" class="btn-publish">
            发布文章
          </el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import articleApi from '~/api/article'

const defaultForm = {
  title: '',
  content: '',
  cover: '',
}

export default {
  layout: 'blank',
  components: {Editor, Toolbar},
  data() {
    return {
      articleInfo: {...defaultForm},
      saveBtnDisabled: false,
      editor: null,
      titleLength: 0,
      titleError: '',
      toolbarConfig: {
        excludeKeys: ['uploadVideo', 'group-video'],
      },
      editorConfig: {
        placeholder: '请在此输入文章正文内容...',
        MENU_CONF: {
          uploadImage: {
            server: 'http://localhost:8000/api/oss/upload',
            fieldName: 'file',
            maxFileSize: 2 * 1024 * 1024,
            allowedFileTypes: ['image/jpeg', 'image/png'],
            customInsert: (res, insertImgFn) => {
              // res 就是服务器返回的整个对象
              if (res.success && res.data) {
                insertImgFn(res.data)  // 直接传字符串地址
              } else {
                alert('图片上传失败，请重试')
              }
            },
            onSuccess(file, res) {
              console.log('上传成功', res)
            },
            onFailed(file, res) {
              console.error('上传失败', res)
            },
          }
        },
      },
    }
  },
  methods: {
    checkTitleLength() {
      this.titleLength = this.articleInfo.title.length
      if (this.titleLength < 5) {
        this.titleError = '标题长度不能少于5个字符'
        this.saveBtnDisabled = true
      } else if (this.titleLength > 50) {
        this.titleError = '标题长度不能超过50个字符'
        this.saveBtnDisabled = true
      } else {
        this.titleError = ''
        this.saveBtnDisabled = false
      }
    },
    onEditorCreated(editor) {
      this.editor = editor
    },
    beforeDestroy() {
      if (this.editor) {
        this.editor.destroy()
        this.editor = null
      }
    },
    beforeCoverUpload(file) {
      const isValid = ['image/jpeg', 'image/png'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isValid) this.$message.error('仅支持 JPG/PNG 格式图片！')
      if (!isLt2M) this.$message.error('图片大小不能超过 2MB！')
      return isValid && isLt2M
    },
    handleCoverSuccess(response) {
      if (response.code === 20000) {
        this.articleInfo.cover = response.data
        this.$message.success('封面上传成功')
      } else {
        this.$message.error('封面上传失败：' + response.message)
      }
    },
    handleBack() {
      this.$confirm('是否将当前内容保存为草稿？', '提示', {
        confirmButtonText: '保存',
        cancelButtonText: '不保存',
        distinguishCancelAndClose: true,
        type: 'warning',
      })
        .then(() => {
          this.saveAsDraft().then(() => {
            this.$router.go(-1)
          })
        })
        .catch((action) => {
          if (action === 'cancel') {
            this.$router.go(-1)
          }
        })
    },
    publishArticle() {
      this.saveOrUpdate('publish')
    },
    saveAsDraft() {
      this.saveOrUpdate('draft')
    },
    async saveOrUpdate(type) {
      if (!this.articleInfo.title) {
        this.$message.error('请输入文章标题')
        return
      }
      if (!this.articleInfo.content) {
        this.$message.error('请输入文章正文')
        return
      }

      const saveType = {
        publish: '发布',
        draft: '保存为草稿',
      }

      // 设置 status 字段，根据类型传递枚举字符串
      this.articleInfo.status = type === 'draft' ? 'Draft' : 'Normal'

      try {
        await articleApi.publishArticle(this.articleInfo)
        this.$message.success(`文章${saveType[type]}成功`)

        if (type === 'publish') {
          // 发布后跳转文章列表页
          this.$router.push('/community/article')
        }
        if(type === 'draft') {
          this.$router.push('/community/article')
        }
      } catch (error) {
        this.$message.error(`文章${saveType[type]}失败：` + (error.message || '未知错误'))
      }
    },
  },
}
</script>

<style scoped>
* {
  box-sizing: border-box;
}

.app-container {
  max-width: 1200px;
  background: #fff;
  padding: 30px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  margin: 0 auto;
  position: relative;
}

/* 返回蓝色文字链接 */
.back-link {
  position: absolute;
  left: 30px;
  top: 30px;

  font-size: 16px;
  color: #409EFF;
  cursor: pointer;

  text-decoration: none !important;
  border: none !important;
  border-bottom: none !important;
  box-shadow: none !important;
  outline: none !important;
  background: transparent !important;
}

/* 防止聚焦、悬浮时显示下划线或轮廓线 */
.back-link:hover,
.back-link:focus,
.back-link:active {
  text-decoration: none !important;
  outline: none !important;
  border-bottom: none !important;
  box-shadow: none !important;
}

.form-title {
  font-size: 30px;
  font-weight: bold;
  margin-bottom: 40px;
  color: #2c3e50;
  text-align: center;
}

.article-form ::v-deep .el-form-item {
  margin-bottom: 30px;
}

.article-title-input >>> .el-input__inner {
  font-size: 28px;
  font-weight: bold;
  color: #1a1a1a;
  height: 50px;
  padding: 20px;
  background-color: #fdfdfd;
  border-radius: 8px;
  border: 1px solid #dcdfe6;
}

.title-error {
  color: #f56c6c;
  margin-top: 8px;
  font-size: 14px;
}

.editor-container {
  width: 100%;
  height: 600px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  overflow: hidden;
  background: #ffffff;
}

.editor-toolbar {
  border-bottom: 1px solid #dcdfe6;
  padding: 10px;
  background-color: #f5f7fa;
}

.editor-content {
  min-height: 300px;
  padding-left: 10px;
  font-size: 18px;
  line-height: 1.8;
  color: #1a1a1a;
  background-color: #ffffff;
}

.cover-align {
  margin-left: 0;
}

.cover-uploader {
  width: 500px;
  height: 260px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.cover-image {
  width: 500px;
  height: 260px;
  border-radius: 12px;
  object-fit: cover;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.upload-placeholder {
  width: 500px;
  height: 260px;
  border: 2px dashed #dcdfe6;
  border-radius: 12px;
  background-color: #f9f9f9;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.cover-uploader-icon {
  font-size: 36px;
  margin-bottom: 10px;
}

.upload-text {
  font-size: 16px;
}

.upload-hint {
  font-size: 12px;
  margin-top: 6px;
}

/* 按钮组样式 */
.btn-group {
  display: flex;
  gap: 15px;
  justify-content: center;
}

.btn-save-draft {
  background-color: #67c23a;
  border-color: #67c23a;
  color: #fff;
}

.btn-save-draft:hover {
  background-color: #5fb82e;
}

.btn-publish {
  background-color: #409EFF;
  border-color: #409EFF;
  color: #fff;
}

.btn-publish:hover {
  background-color: #337ecc;
}
</style>
